<?php

namespace app\index\controller\wechat;

use app\index\service\WechatSubscription;
use ShidianUtil\Utils\ConvertUtil;
use think\APP;
use think\facade\Config;
use think\facade\Log;

/**
 * 微信公众号
 * Class Subscription
 * @package app\index\controller\wechat
 */
class Subscription
{
    private WechatSubscription $wechatSubscription;

    public function __construct(WechatSubscription $wechatSubscription)
    {

        $this->wechatSubscription = $wechatSubscription;
    }

    /**
     * 公众号回调
     * @url /wechat/subscription/index
     * @return mixed|string|\think\response\Xml
     */
    public function index()
    {
        if (isset($_GET['echostr'])) {
            return $_GET['echostr'];
        }

        $config = Config::get('wechat.' . SUBSCRIPTION, []);

        $token = $config['Token'];
        $encodingAESKey = $config['EncodingAESKey'];

        // 验签

        $xml = file_get_contents('php://input');
        $result = null;

        if (strlen($xml) > 0) {

            // 记录参数
            Log::info('微信回调 ' . $xml);
            $input = ConvertUtil::xmlDecode($xml);

            $result = $this->wechatSubscription->handle($input);
        }

        if (is_null($result)) {
            return 'success';
        }

        if (is_array($result)) {
            return xml($result, 200, [], ['root_node' => 'xml']);
        }

        return $result;
    }
}
